<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 飞地的思路也很简单，甚至更简单点
                只需要先遍历下，让周边的地和相邻的地变为海洋即可
            */
            var numEnclaves = function (grid) {
                let m = grid.length
                let n = grid[0].length

                /* dfs的作用：遍历四周，然后让其置为0或者1  flag只是为了少写一次dfs，因为它要计的是单元格总数 */
                let count = 0
                function dfs(i, j, flag) {
                    if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0) {
                        return
                    }
                    if (flag) {
                        count++
                    }
                    grid[i][j] = 0
                    dfs(i - 1, j, flag)
                    dfs(i + 1, j, flag)
                    dfs(i, j - 1, flag)
                    dfs(i, j + 1, flag)
                }

                for (let i = 0; i < m; i++) {
                    for (let j = 0; j < n; j++) {
                        if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {
                            if (grid[i][j] == 1) {
                                dfs(i, j, false)
                            }
                        }
                    }
                }

                for (let i = 0; i < m; i++) {
                    for (let j = 0; j < n; j++) {
                        if (grid[i][j] == 1) {
                            dfs(i, j, true)
                        }
                    }
                }
                return count
            }
            console.log(
                numEnclaves([
                    [0, 1, 1, 0],
                    [0, 0, 1, 0],
                    [0, 0, 1, 0],
                    [0, 0, 0, 0],
                ])
            )
        </script>
    </body>
</html>
